﻿using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using DevExpress.XtraTab.ViewInfo;
using BCL.BaseLib;
using BCL.BaseLib.Basics;
using BCL.Tool;
using System;
using System.Linq;
using System.Windows.Forms;

namespace BCL.Component
{
    public partial class MainTable : XtraUserControl, ICustom
    {
        public MainTable()
        {
            InitializeComponent();
            xtraTabControl1.AppearancePage.Header.Font = new System.Drawing.Font("微软雅黑", 10F);
            xtraTabControl1.AppearancePage.HeaderActive.Font = new System.Drawing.Font("微软雅黑", 10F);
            this.xtraTabControl1.CloseButtonClick += XtraTabControl1_CloseButtonClick;
        }

        private void XtraTabControl1_CloseButtonClick(object sender, EventArgs e)
        {
            XtraTabPage page = (XtraTabPage)sender;
            FunctionEntity fe = page.Tag as FunctionEntity;
            fe.Control?.ControlCloseing();
        }

        public bool FunctionInvoke(Form mainFrom, FunctionEntity fe)
        {
            if ((fe.Control.Setting & FunctionControlSetting.UserControl) != 0)
            {
                if (xtraTabControl1.TabPages.Any(o => o.Text == fe.Title))
                {
                    this.xtraTabControl1.SelectedTabPage = xtraTabControl1.TabPages.First(o => o.Text == fe.Title);
                    if(fe.IsReload)
                        fe.Control.ReloadData(fe.ItemParamter);
                }
                else
                {
                    XtraTabPage page = new XtraTabPage();
                    page.Tag = fe;
                    page.Text = fe.Title.Language();
                    fe.Control.Dock = DockStyle.Fill;
                    page.BorderStyle = BorderStyle.None;
                    fe.Control.Function = fe;
                    fe.Control.BorderStyle = BorderStyle.None;
                    page.Controls.Add(fe.Control);
                    xtraTabControl1.TabPages.Add(page);
                    xtraTabControl1.SelectedTabPage = page;
                    tabControlChanged?.Invoke(fe,1);
                }
            }
            return true;
        }

        public void Select(FunctionEntity fe)
        {
            XtraTabPage page = xtraTabControl1.TabPages.FirstOrDefault(o=>o.Tag==fe);
            if(page!=null)
                xtraTabControl1.SelectedTabPage = page;
        }

        private void xtraTabControl1_CloseButtonClick(object sender, EventArgs e)
        {
            ClosePageButtonEventArgs cpb = (ClosePageButtonEventArgs)e;
            XtraTabPage xp = (XtraTabPage)cpb.Page;
            this.xtraTabControl1.TabPages.Remove(xp);
            xp.Dispose();
            tabControlChanged?.Invoke(xp.Tag as FunctionEntity, 1);
        }



        private Action<FunctionEntity, int> tabControlChanged;
        public event Action<FunctionEntity, int> TabControlChanged
        {
            add { tabControlChanged += value; }
            remove { tabControlChanged -= value; }
        }


    }
}
